/*
 * FlotChoice.scala
 *
 * To change this template, choose Tools | Template Manager
 * and open the template in the editor.
 */

package net.liftweb.widgets.flot

import scala.xml.{NodeSeq, Node, PCData, Text, Unparsed}

import net.liftweb.http.js.{JsCmds, JsCmd}
import net.liftweb.http.js.jquery.{JqJE, JqJsCmds}

/**
 * render JS and HTML the let the users choose which series to graph
 */

class FlotChoice (idChoices : String, optional : List [Boolean])
  extends FlotCapability {

    def renderBefore (flotInfo : FlotInfo) : JsCmd = {

        // if no color is set in Scala code, generate JS to set color to a fix value
        val colorSet = flotInfo.series.exists(
            serie => serie.color match {
                case None => false
                case _ => true
            }
          )

        if (colorSet)
          JsCmds.Noop
        else {
          val js = "jQuery.each (datas_" + flotInfo.idPlaceholder + ", function(index, val) {val.color = index;});"
          JsCmds.Run (js)
        }
    }

    def renderAfter (flotInfo : FlotInfo) : JsCmd = {

      // creates the input checkbox the choice
      val jsSetInputCheckBox = JqJsCmds.JqSetHtml(idChoices, _renderHtml (flotInfo))

      // the series that the user cannot switch off
      val alwaysVisibled =
       (flotInfo.series.indices zip optional).
         filter (zip => ! zip._2).
         map (zip => "datas_" + flotInfo.idPlaceholder + " [" + zip._1 + "]").
         mkString (", ")

      val lenghtNameChoice = 6 + flotInfo.idPlaceholder.length // show_ph_graph_X -> 14

      val js = """
var choiceContainer = $('#""" + idChoices + """');
choiceContainer.find("input").click(plotAccordingToChoices);

function plotAccordingToChoices() {
  var data = [""" + alwaysVisibled + """];

  choiceContainer.find("input:checked").each(function () {
    var key = $(this).attr("name");

    if (key) {
      var id = key.substring (""" + lenghtNameChoice + """ ) ;

      if (datas_""" + flotInfo.idPlaceholder + """ [id])
        data.push(datas_"""  + flotInfo.idPlaceholder + """ [id]);
    }
  });

  if (data.length > 0)
    jQuery.plot(jQuery('#' +'ph_graph'), data, options_ph_graph) ;
}
"""
        
       jsSetInputCheckBox & JsCmds.Run (js)
    }

  // TO-DO: templates this
  private def _renderHtml (flotInfo : FlotInfo) : NodeSeq = {
    val optionalSeries : List [Pair [String, String]] =
       (flotInfo.series.indices zip optional zip flotInfo.series).
         filter (zip => zip._1._2).
         map (zip => ("show_" + flotInfo.idPlaceholder + "_" + zip._1._1, zip._2.label match {case Some (x) => x ; case None => ""}))

    <xml:group>
        {
            optionalSeries.flatMap (opt =>
                <input type='checkbox' checked='checked' name={opt._1}></input>
                <span>{opt._2}</span>
            )
        }
    </xml:group>
  }

  //
  def renderHtml (flotInfo : FlotInfo)  : NodeSeq = {
      Text ("")
  }

  def renderHide () : JsCmd = {
      JsCmds.Noop
  }

  def renderShow () : JsCmd = {
      JsCmds.Noop
  }
}
